package com.kuizii.server.net;

import com.kuizii.common.net.LiteRegisterRequest;
import com.kuizii.server.discovery.RegisterEvent;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.springframework.context.ApplicationContext;

import java.util.List;

/**
 * @author renxiaodong
 */
public class DefaultMessageReceiverHandler extends ByteToMessageDecoder {
    ApplicationContext applicationContext;

    public DefaultMessageReceiverHandler(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Client " + ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println("发生解码异常");
        cause.printStackTrace();
        ctx.fireExceptionCaught(cause);
//        ctx.close();
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        System.out.println("接收消息 " + byteBuf.toString());
//        channelHandlerContext.writeAndFlush("ACK");

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        LiteRegisterRequest request = (LiteRegisterRequest) msg;
        RegisterEvent registerEvent = new RegisterEvent(request.getEventType(), request.getRegistration());
        applicationContext.publishEvent(registerEvent);

        System.out.println("接收消息 " + msg.toString());
        //写回信息
    }


}
